package dshumsky.jooq;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class SpringConfig {

	@Bean(name = "dataSource")
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setUrl("jdbc:mysql://localhost:3306/bot");
		dataSource.setUsername("root");
		dataSource.setPassword("password");
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		return dataSource;
	}

	@Bean(name = "transactionManager")
	public PlatformTransactionManager transactionManager() {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource());
		return transactionManager;
	}

	@Bean(name = "transactionAwareDataSource")
	public TransactionAwareDataSourceProxy transactionAwareDataSource() {
		TransactionAwareDataSourceProxy transactionAwareDataSource = new TransactionAwareDataSourceProxy(
				dataSource());
		return transactionAwareDataSource;
	}

	// -----------------------------------------------------------

	@Bean(name = "jooqConnectionProvider")
	public DataSourceConnectionProvider connectionProvider() {
		DataSourceConnectionProvider connectionProvider = new DataSourceConnectionProvider(
				transactionAwareDataSource());
		return connectionProvider;
	}

	@Bean(name = "jooqConfiguration")
	public DefaultConfiguration jooqConfiguration() {
		DefaultConfiguration configuration = new DefaultConfiguration();
		configuration.setConnectionProvider(connectionProvider());
		configuration.set(SQLDialect.MYSQL);
		return configuration;
	}

	@Bean(name = "jooqDsl")
	public DefaultDSLContext jooqDsl() {
		DefaultDSLContext dsl = new DefaultDSLContext(jooqConfiguration());
		return dsl;
	}

}
